package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.hmdp.utils.RedisConstants.TYPE_LIST_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public Result<List<ShopType>> queryTypeList() {
        //从缓存中查找
        String typeListJson = stringRedisTemplate.opsForValue().get(TYPE_LIST_KEY);
        //缓存中存在则直接返回
        if(StrUtil.isNotBlank(typeListJson)){
            List<ShopType> list = JSONUtil.toList(typeListJson, ShopType.class);
            return Result.ok(list);
        }
        //不存在则查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();
        //数据库中存在
        if(typeList==null){
            return Result.fail("商城列表不存在");
        }
        //存入redis中
        typeListJson = JSONUtil.toJsonStr(typeList);
        stringRedisTemplate.opsForValue().set(TYPE_LIST_KEY,typeListJson);
        //返回
        return Result.ok(typeList);
    }
}
